import Axios from 'axios';
// import { isPlainObject } from 'lodash/lang';
// import { camelizeKeys, snakeizeKeys } from './transforms';
import StorageUtils from './StorageUtils';
import { Modal } from 'antd';
// import { errorCodeMsgs } from '@/consts/RequestErrorCode';

const axios = Axios.create({
  //自动给请求的url加上webpack.xx.config.js中配置的url前缀.
  baseURL: `${process.env.BASE_URL}`,
  //请求和响应默认使用json格式.
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  responseType: 'json'
  //请求时,把参数命名格式从Camel转成Snake.
  // transformRequest(data) {
  //   if (isPlainObject(data)) return JSON.stringify(snakeizeKeys(data));
  //   return data;
  // },
  //接收响应内容时,把参数命名格式从Snake转成Camel.
  // transformResponse(data) {
  //   // data comes as string in IE
  //   if (typeof data === 'string' && data.length) data = JSON.parse(data);
  //   return camelizeKeys(data);
  // }
});

// 添加请求拦截器, 在发送请求之前做些什么
axios.interceptors.request.use(function (config) {
  //在request的http-header中存入用户的session_id.后台shiro用于校验权限
  if (StorageUtils.getSessionItem('session') != null) {
    // config.headers['JSESSIONID'] = session_id;
    const session_id = StorageUtils.getSessionItem('session').session_id;
    // console.log('current user\'s sessionInfo', StorageUtils.getSessionItem('session'));
    config.headers['SessionId'] = session_id;
  }
  console.log('the request which axios dispatch to server:', config);
  return config;
}, function (error) {
  // 对请求错误做些什么(服务器没收到请求)
  return Promise.reject(error);
});

// 添加响应拦截器.对响应数据做点什么
axios.interceptors.response.use(function (response) {
  //2xx
  console.log('the normal response from the server:', response);
  return response;
}, function (error) {
  //error对象中包含config,request,response三个对象.
  // console.log(Object.entries(error));
  const resp = error.response;
  console.log('the error response from the server:', resp);
  console.log(`${resp.config.method}请求${resp.config.url}时,发生错误: ${resp.status} ${resp.statusText} \r\n`);
  // const errorText = errorCodeMsgs[resp.status] || resp.statusText;

  if(resp.status === 401) {
    // console.log('history:', window.history.length);
    // console.log('this.context', history.pushState({}, 'login', '/home/user'));
    Modal.warning({
      title: '警告',
      content: '尚未登录或者会话超时,即将重新登录...',
      onOk:() => {
        sessionStorage.clear();
        window.location.href = '/login';
      }
    });
    return Promise.reject(error);
  }
  
  // notification.error({
  //   message:`请求${resp.config.url}时,发生错误: ${resp.status}`,
  //   description:errorText
  // });

  return Promise.reject(error);
});

export default axios;
